<?php
/**
 * payment.php
 *
 * Author: netman
 * DateTime:  2023/10/20 14:57
 */

trait Trait_Api_Payment
{


    /**
     * @function 零元支付
     * @param $ordersn
     * @param  string  $payMethod
     * @return mixed
     */
    public function zero_pay($ordersn, $payMethod = '0元下单')
    {
        if (St_Functions::is_normal_app_install('system_card')) {
            $is_card_order = DB::select()->from('card_member_reservation_record')->where("order_sn='{$ordersn}'")->execute()->valid();
            if ($is_card_order) {
                $payMethod = '会员卡抵扣';
            }
        }
        $status = St_Payment::change_order($ordersn, $payMethod);
        if ($status) { // 支付处理成功
            $this->child_order_change_status($ordersn, $payMethod);
            $sign = '24';
            return array('status' => true, 'data' => ['sign' => $sign], 'msg' => '订单支付成功');
        } else {// 支付处理失败
            return array('status' => false, 'msg' => '订单支付失败');
        }
    }

    /**
     * @function 子订单状态更改.
     * @param $ordersn
     * @param $paymethod
     */
    private function child_order_change_status($ordersn, $paymethod)
    {
        $parent_order = DB::select()->from('member_order')->where('ordersn', '=', $ordersn)->execute()->current();
        if ($parent_order['id']) {
            $child_order = DB::select()->from('member_order')->where('pid', '=',
                $parent_order['id'])->execute()->as_array();
            foreach ($child_order as $child) {
                $this->change_order($child['ordersn'], $paymethod);
            }
        }
    }

    /**
     * 线上支付修改订单状态
     * @function
     * @param $ordersn
     * @param $payMethod
     * @param  int  $new_status
     * @return bool
     */
    private function change_order($ordersn, $payMethod, $new_status = 2)
    {
        $status = false;
        $product_model = '';
        $order_info = DB::select('status', 'typeid')->from('member_order')->where('ordersn', '=',
            $ordersn)->execute()->current();
        $org_status = $order_info['status'];
        if ( ! in_array($org_status, array(1, 3))) {
            return false;
        }
        if ($org_status == 3) {
            $product_model = St_Product::get_product_model($order_info['typeid']);
        }

        //更改订单状态
        $rows = DB::update('member_order')
            ->where('ordersn', '=', "{$ordersn}")
            ->set(array('status' => $new_status, 'paysource' => $payMethod, 'paytime' => time()))
            ->execute();
        if ($rows == 1) {
            $order_info = DB::select()->from('member_order')->where('ordersn', '=', $ordersn)->execute()->current();
            Model_Member_Order::back_order_status_changed($org_status, $order_info, $product_model);
            $status = true;
        }
        return $status;
    }

    /**
     * @function 检测订单是否正确
     * @param $ordersn
     * @return array
     */
    public function ordersn_checked($ordersn)
    {
        $bool = false;
        $info['ordersn'] = $ordersn;
        $info['id'] = '';
        $err = '';
        if ($ordersn || ! empty($ordersn)) {
            $order_info = Model_Member_Order::order_info($ordersn);
            if ($order_info) {
                $info['id'] = $order_info['id'];
                $product_info = Model_Model::get_product_bymodel($order_info['typeid'], $order_info['productautoid'],
                    'id');
            }
        }

        if ( ! $ordersn || empty($ordersn)) {
            //订单号为空
            $info['sign'] = 26;
            $err = self::ORDERSN_ERROR;
        } else {
            if (empty($product_info) || empty($product_info[0]) || empty($product_info[0]['id'])) {
                //订单号格式错误
                $info['sign'] = 28;
                $err = "订单{$ordersn}".self::PRODUCT_NOT_EXISTS;
            } else {
                if ( ! preg_match('~^\d+$~', $ordersn)) {
                    //订单号格式错误
                    $info['sign'] = 25;
                    $err = "订单{$ordersn}".self::ORDERSN_FORMAT_ERROR;
                } else {
                    if (Model_Member_Order::not_exists($ordersn)) {
                        //订单不存在
                        $info['sign'] = 26;
                        $err = "订单{$ordersn}".self::ORDERSN_NOT_EXISTS;
                    } else {
                        if (Model_Member_Order::payed($ordersn)) {
                            //订单已支付
                            $info['sign'] = 24;
                            $err = "订单{$ordersn}".self::ORDERSN_PAYED;
                        } else {
                            if ($order_info['status'] != 1) {
                                //只有等待支付订单才能进行支付.
                                $info['sign'] = 27;
                                $err = "订单{$ordersn}".self::POST_ERROR;
                            } else {
                                if ( ! Model_Model::check_usedate($order_info)) {
                                    // 支付时间需在订单最晚预订时间内
                                    $info['sign'] = 29;
                                    $err = "订单{$ordersn}".self::ORDERSN_TIME_OUT;
                                } else {
                                    if ($this->check_depot_three_out($order_info)) {
                                        // 库存已不足够
                                        $info['sign'] = 44;
                                        $err = "订单{$ordersn}".self::ORDERSN_NOT_DEPOT;
                                    } else {
                                        if ($this->check_depot_three_uhcms_out($order_info)) {
                                            // 库存已不足够
                                            $info['sign'] = 45;
                                            $err = "订单{$ordersn}".self::ORDERSN_NOT_DEPOT;
                                        } else {
                                            $bool = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return array('status' => $bool, 'msg' => $err, 'data' => $info);
    }

    /**
     * @function 检测STCCS库存是否不足
     * @param $info
     * @return bool
     */
    private function check_depot_three_out($info)
    {
        try {
            $typeid = $info['typeid'];
            if (St_Functions::is_normal_app_install('supplier_spot_stccs')) {
                //门票库存检查
                if ($typeid == 5) {
                    $dingnum = $info['dingnum'];
                    $ticketid = $info['suitid'];
                    //获取第三方门票库存
                    $api = new Unified_Stccs();
                    //$ticketid = 50;
                    $result = $api->stccs_depot_number($ticketid, $info['usedate'], $info['usedate']);
                    $result = json_decode($result);
                    if (isset($result->data)) {
                        foreach ($result->data as $v) {
                            $real_num = $v;
                        }
                        if ($real_num < $dingnum) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 检查uhcms库存
     * @param $info
     * @return bool
     */
    private function check_depot_three_uhcms_out($info)
    {
        try {
            $typeid = $info['typeid'];
            $installis = St_Functions::is_normal_app_install('supplier_hotel_uhcms');

            if ($installis) {
                //酒店库存检测
                if ($typeid == 2) {
                    $dingnum = $info['dingnum'];
                    $suitid = $info['suitid'];

                    //及时获取uhcms的库存
                    $params = array();
                    $params['hotelid'] = $info['productautoid'];
                    $params['roomid'] = $suitid;
                    $params['check_in'] = $info['usedate'];
                    $params['check_out'] = $info['departdate'];
                    $nums = Unified_Uhcms::depot_number($params);
                    if ($nums < $dingnum) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }


}